<template>
    <div style="display: flex; gap: 20px; padding: 20px;">
        <!-- 左侧表单 -->
        <div style="flex: 1;">
            <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="auto" style="max-width: 600px;">
                <!-- 基础信息 -->
                <h3>基础信息</h3>

                <el-form-item label="到票单号">
                    <div style="display: flex; justify-content: center;">
                        <el-input v-model="formData.ticketCode" :disabled="autoGenerate" />
                        <el-checkbox v-model="autoGenerate" style="margin-left: 10px;">系统编号</el-checkbox>
                    </div>
                </el-form-item>

                <el-form-item label="到票主体">
                    <el-input v-model="formData.ticketName" />
                </el-form-item>

                <el-form-item label="到票类型">
                    <el-select style="width: 300px;" v-model="formData.ticketType" placeholder="" clearable>
                        <el-option label="专用发票" value="专用发票" />
                        <el-option label="普通发票" value="普通发票" />
                        <el-option label="电子发票" value="电子发票" />
                        <el-option label="其他" value="其他" />
                    </el-select>
                </el-form-item>



                <el-form-item label="开票方">
                    <el-select style="width: 300px;" v-model="formData.receiveTicket" placeholder="" clearable>
                        <el-option label="白读公司" value="白读公司" />
                        <el-option label="梅团公司" value="梅团公司" />
                        <el-option label="腾旭公司" value="腾旭公司" />
                        <el-option label="景东公司" value="景东公司" />
                    </el-select>
                </el-form-item>

                <el-form-item label="到票时间">
                    <el-date-picker type="date" v-model="formData.ticketDate" value-format="YYYY-MM-DDTHH:mm:ss.SSSZ" />
                </el-form-item>

                <el-form-item label="备注">
                    <el-input v-model="formData.ticketDesc" type="textarea" />
                </el-form-item>

                <!-- 加工工序 -->
                <h3>订单</h3>
                <div style="display: flex; gap: 10px; margin-bottom: 10px;">
                    <el-button type="primary" size="small" @click="showAddStepDialog = true">添加</el-button>
                    <el-button type="danger" size="small" @click="removeSelectedSteps()">移除</el-button>
                </div>

                <el-table :data="procedures" style="width: 100%; min-width: 800px; overflow-x: auto;" border
                    @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column label="序号" width="80">
                        <template #default="{ $index }">
                            {{ $index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column label="订单编号" min-width="120">
                        <template #default="{ row }">
                            {{ row.orderCode }}
                        </template>
                    </el-table-column>
                    <el-table-column label="订单数量" min-width="120">
                        <template #default="{ row }">
                            {{ row.orderNum }}
                        </template>
                    </el-table-column>
                    <el-table-column label="订购物品" min-width="150">
                        <template #default="{ row }">
                            {{ row.orderGoods }}
                        </template>
                    </el-table-column>
                    <el-table-column label="总金额" min-width="120">
                        <template #default="{ row }">
                            {{ row.allmomeny }}
                        </template>
                    </el-table-column>
                    <el-table-column label="已付金额" min-width="120">
                        <template #default="{ row }">
                            {{ row.tomomeny }}
                        </template>
                    </el-table-column>
                    <el-table-column label="付款金额" min-width="150">
                        <template #default="{ row }">
                            <el-input v-model="row.invoiceAmount" size="small" style="width: 100%;" />
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" min-width="200" fixed="right">
                        <template #default="{ $index }">
                            <el-button size="small" @click="moveUp($index)">上移</el-button>
                            <el-button size="small" @click="moveDown($index)">下移</el-button>
                            <el-button size="small" type="danger" @click="removeStep($index)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div style="text-align: right; margin-top: 20px;">
                    <el-button @click="resetForm(ruleFormRef)">关闭</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
                </div>
            </el-form>
        </div>

        <!-- 右侧添加工序弹窗 -->
        <el-dialog title="添加订单" v-model="showAddStepDialog" width="1000px">
            <el-table :data="availableSteps" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="序号" width="60">
                    <template #default="{ $index }">
                        {{ $index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column label="销售订单编号" min-width="120">
                    <template #default="{ row }">
                        {{ row.orderCode }}
                    </template>
                </el-table-column>
                <el-table-column label="下单人" min-width="120">
                    <template #default="{ row }">
                        {{ row.createrPeople }}
                    </template>
                </el-table-column>
                <el-table-column label="订单状态" min-width="120">
                    <template #default="{ row }">
                        {{ getOrderStatus(row.orderState) }}
                    </template>
                </el-table-column>
                <el-table-column label="下单商品" min-width="150">
                    <template #default="{ row }">
                        {{ row.orderGoods }}
                    </template>
                </el-table-column>
                <el-table-column label="订单数量" min-width="120">
                    <template #default="{ row }">
                        {{ row.orderNum }}
                    </template>
                </el-table-column>
            </el-table>

            <div style="margin-top: 20px; text-align: right;">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="totalSteps"
                    layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"></el-pagination>
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showAddStepDialog = false">取消</el-button>
                    <el-button type="primary" @click="addSelectedSteps">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, watch, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import axios from 'axios'
import router from '@/router'

// ==================== 接口返回数据类型定义 ====================
interface OrderStep {
    id: number;
    orderCode: string;
    orderSon: string;
    orderState: number;
    orderNum: number;
    orderGoods: string;
    allmomeny: number;
    tomomeny: number;
    clientId: number;
    isOrder: boolean;
    createrPeople: string;
    createTime: Date;
    updaterPeople: string;
    updateTime: Date;
    isDel: boolean;
    remark?: string;
    invoiceAmount?: string; // 付款金额字段
}

interface ProcessResponse {
    totalcount: number;
    totalPage: OrderStep[];
}

// ==================== 表单数据 ====================
const ruleFormRef = ref<FormInstance>()
const formData = reactive({
    ticketCode: "",
    ticketName: "",
    ticketType: "",
    ticketDate: "",
    ticketMomeny: "0",
    receiveTicket: "",
    ticketDesc: "",
    createrPeople: "",
    createTime: "",
    updaterPeople: "",
    updateTime: "",
    procedures: [] as any[]
})

// 自动生成编号
const autoGenerate = ref(false)
watch(autoGenerate, (val) => {
    if (val) {
        formData.ticketCode = `CS${Date.now()}${Math.floor(Math.random() * 10000)}`
    } else {
        formData.ticketCode = ''
    }
})

// 加工工序列表（已选）
const procedures = ref<OrderStep[]>([])
// 添加工序弹窗
const showAddStepDialog = ref(false)

// 可用工序列表
const availableSteps = ref<OrderStep[]>([])
const totalSteps = ref(0)
const currentPage = ref(1)
const pageSize = ref(5)

const fetchAvailableSteps = () => {
    axios.get<ProcessResponse>(`/api/InvoiceTicket/Getorder`, {
        params: {
            Index: currentPage.value,
            size: pageSize.value
        }
    })
        .then(res => {
            availableSteps.value = res.data.totalPage || []
            totalSteps.value = res.data.totalcount
        })
        .catch(err => console.error('获取订单失败:', err))
}

// 事件处理
const selectedStepIds = ref<number[]>([])

const handleSelectionChange = (selection: OrderStep[]) => {
    selectedStepIds.value = selection.map(s => s.id)
}

const addSelectedSteps = () => {
    const newSteps = availableSteps.value.filter(step => selectedStepIds.value.includes(step.id))
    procedures.value.push(...newSteps)
    showAddStepDialog.value = false
    selectedStepIds.value = []
}

const removeStep = (index: number) => {
    procedures.value.splice(index, 1)
}

const moveUp = (index: number) => {
    if (index > 0) {
        const temp = procedures.value[index]
        procedures.value[index] = procedures.value[index - 1]
        procedures.value[index - 1] = temp
    }
}

const moveDown = (index: number) => {
    if (index < procedures.value.length - 1) {
        const temp = procedures.value[index]
        procedures.value[index] = procedures.value[index + 1]
        procedures.value[index + 1] = temp
    }
}

const removeSelectedSteps = () => {
    procedures.value = procedures.value.filter(step => !selectedStepIds.value.includes(step.id))
    selectedStepIds.value = []
}

const handleSizeChange = (val: number) => {
    pageSize.value = val
    fetchAvailableSteps()
}

const handleCurrentChange = (val: number) => {
    currentPage.value = val
    fetchAvailableSteps()
}

const getOrderStatus = (status: number): string => {
    switch (status) {
        case 0: return '待处理'
        case 1: return '处理中'
        case 2: return '已完成'
        case 3: return '已取消'
        default: return '未知状态'
    }
}

// 表单验证规则
const rules = reactive<FormRules>({
    ticketCode: [
        { required: true, message: '请输入出差单号', trigger: 'blur' }
    ],
    ticketName: [
        { required: true, message: '请输入出差主体', trigger: 'blur' }
    ],
    ticketType: [
        { required: true, message: '请选择出差类型', trigger: 'change' }
    ],
    ticketMomeny: [
        { required: true, message: '请输入出差金额', trigger: 'blur' }
    ]
})

// 处理付款请求
const processPayments = (orders: OrderStep[]): Promise<void> => {
    // 过滤出有付款金额的订单
    const ordersToProcess = orders.filter(order => order.invoiceAmount && Number(order.invoiceAmount) > 0);

    if (ordersToProcess.length === 0) {
        return Promise.resolve();
    }

    // 创建一个Promise数组，每个元素代表一个付款请求
    const paymentPromises = ordersToProcess.map(order => {
        // 准备付款数据
        const paymentData = {
            invoiceAmount: order.invoiceAmount,
            orderId: order.id
        };

        // 返回一个Promise
        return axios.post('/api/InvoiceTicket/AddInvoicePayment', paymentData)
            .then(response => {
                console.log(`订单 ${order.orderCode} 付款成功，返回数据:`, response.data);
                return response;
            })
            .catch(err => {
                console.error(`订单 ${order.orderCode} 付款失败:`, err);
                throw new Error(`订单 ${order.orderCode} 付款失败: ${err.message}`);
            });
    });

    // 等待所有付款处理完成
    return Promise.all(paymentPromises)
        .then(() => {
            console.log('所有付款处理完成');
            return;
        });
};

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            const payload = {
                ticketCode: formData.ticketCode,
                ticketName: formData.ticketName,
                ticketType: formData.ticketType,
                ticketDate: formData.ticketDate,
                ticketDesc: formData.ticketDesc,
                ticketMomeny: formData.ticketMomeny,
                receiveTicket: formData.receiveTicket,
                createrPeople: "系统",
                createTime: new Date().toISOString(),
                updaterPeople: "系统",
                updateTime: new Date().toISOString(),

                procedures: procedures.value.map(step => ({
                    id: step.id, // 确保包含原始订单ID
                    orderCode: step.orderCode,
                    orderSon: step.orderSon || "", // 确保不为null
                    orderState: step.orderState,
                    orderNum: step.orderNum,
                    orderGoods: step.orderGoods || "", // 确保不为null
                    allmomeny: step.allmomeny,
                    tomomeny: step.tomomeny,
                    clientId: step.clientId,
                    isOrder: step.isOrder,
                    createrPeople: step.createrPeople || "系统",
                    createTime: step.createTime || new Date().toISOString(),
                    updaterPeople: step.updaterPeople || "系统",
                    updateTime: step.updateTime || new Date().toISOString(),
                    remark: step.remark || "",
                    // 中间表需要的额外数据
                    OrderId: step.id, // 确保OrderId存在
                    orderTicketRelation: true // 标记为订单与出差单的关系
                }))
            }

            axios.post('/api/InvoiceTicket/AddTicket', payload)
                .then(response => {
                    console.log('提交成功，返回数据:', response.data)

                    // 检查是否有需要付款的订单
                    const ordersWithPayment = procedures.value.filter(order => order.invoiceAmount && Number(order.invoiceAmount) > 0);

                    if (ordersWithPayment.length > 0) {
                        // 处理付款
                        processPayments(ordersWithPayment)
                            .then(() => {
                                ElMessage.success('创建和付款处理完成')
                                resetForm(formEl)
                                procedures.value = []
                            })
                            .catch(payError => {
                                console.error('部分付款处理失败:', payError)
                                ElMessage.warning('数据已保存，但部分付款处理失败')
                            });
                    } else {
                        // 无需付款
                        ElMessage.success('创建成功')
                        resetForm(formEl)
                        procedures.value = []
                    }
                })
                .catch(err => {
                    console.error('提交失败，错误信息:', err)
                    if (err.response?.status === 404) {
                        ElMessage.error('接口不存在，请检查后端服务或路径')
                    } else if (err.response?.status === 400) {
                        ElMessage.error(`请求参数错误: ${err.response?.data?.title || '请检查数据格式'}`)
                        console.error('验证错误详情:', err.response?.data)
                    } else {
                        ElMessage.error(`创建失败: ${err.response?.data?.message || err.message}`)
                    }
                })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (formEl) {
        formEl.resetFields()
    }
    router.push({ path: "/order" })
}

// 页面挂载时初始化
onMounted(() => {
    fetchAvailableSteps()
})
</script>

<style scoped>
.dialog-footer {
    text-align: right;
}
</style>
